import React, { useEffect, useState } from 'react'
import style from './style.module.scss'
import $ from 'jquery'
import subPhoto from '../../../assets/images/subPhoto.png'
import ModalView from '../index'
import { Upload, message } from 'antd'
import { Link } from 'react-router-dom'
import { FileService } from '../../../transfer/service/FileService'
import { CloseOutlined } from '@ant-design/icons'
import { useRecoilState } from 'recoil'
import { SubCard } from '../../Card/SubCard'
import { SubListMock } from '../../Card/SubCard/mock'
import { removeItemAtIndex, pushItem, replaceItemAtIndex } from '../../../utils/RecoilFunctions'
import { CamerasService } from '../../../transfer/service/CamerasSerivce'
import { UserService } from '../../../transfer/service/UserService'

export default function SubPhotoModal() {
    const [width, setWidth] = useState<any>()
    const [height, setHeight] = useState<any>()
    const [fileList, setFileList] = useState<any>([])
    const [count, setCount] = useState(3)
    const [subList, setSubList] = useRecoilState(SubListMock)

    // 初始化自适应
    useEffect(() => {
        setCount($(document).width()! > 1050 ? 5 : 3)
        setWidth($(document).width()! > 1050 ? $(document).width()! * 0.74 + 'px' : $(document).width()! * 0.88 + 'px')
        setHeight($(document).height()! * 0.88 + 'px')
    }, [])

    // 检测是否文件列表是否为空，不为空显示列表
    useEffect(() => {
        if (fileList != '') {
            $(`.${style.center}`).addClass('show')
            $(`.${style.content}`).addClass('show')
            $(`.${style.upload}`).addClass('show')
        } else {
            $(`.${style.center}`).removeClass('show')
            $(`.${style.content}`).removeClass('show')
            $(`.${style.upload}`).removeClass('show')
        }
    }, [fileList])

    // 添加文件是对文件筛选
    const beforeUpload = (file: any) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
            message.error('只能选择图片')
        }
        const isLt5M = file.size / 1024 / 1024 > 1
        if (!isLt5M) {
            message.error('图片至少5MB')
        }
        return isJpgOrPng && isLt5M
    }

    // 上传文件
    const handleUploader = (param: any) => {
        if (!param.file) {
            return false
        }

        let data = new FormData()
        data.append('files', param.file)

        // 上传文件使用的接口方法
        new FileService().uploadFile(data, 'image').then(res => {
            // 获取图片长宽
            const img = new Image()
            let temp: any
            img.src = 'http://localhost:3000/' + res.data.data[0].url
            img.onload = () => {
                // 临时列表
                temp = pushItem(fileList, {
                    id: res.data.data[0].id,
                    hash: res.data.data[0].hash,
                    mime: res.data.data[0].mime,
                    url: res.data.data[0].url,
                    width: img.naturalWidth,
                    height: img.naturalHeight
                })
                setFileList(temp)
            }
        })
    }

    // 移除图片列表
    const handleRemoveImg = (index: number) => {
        console.log(index)
        let subTemp: any = []
        let fileTemp: any = []
        subTemp = removeItemAtIndex(subList, index)
        fileTemp = removeItemAtIndex(fileList, index)
        setSubList(subTemp)
        setFileList(fileTemp)
    }

    //  设置图片数据
    const handleUploadImgData = async () => {
        let temp: any = []
        let isRepeat: boolean = false
        // 上传相机数据
        await subList.map((res: any, index: number) => {
            if (res.cameraId.maker != '' && res.cameraId.model != '') {
                new CamerasService().getCamera(res.cameraId.maker).then(item => {
                    item.data.data.map((camera: any) => {
                        if (camera.model == res.cameraId.model) {
                            isRepeat = true
                            temp = replaceItemAtIndex(subList, index, {
                                userId: JSON.parse(localStorage.getItem('account') as any).id,
                                cameraId: camera.id,
                                imageUrl: res.imageUrl,
                                hash: res.hash,
                                location: res.location,
                                width: res.width,
                                height: res.height,
                                intro: res.intro,
                                focalLength: 0,
                                aperture: 0,
                                iso: 0,
                                tags: res.tags,
                                topics: res.topics
                            })
                            setSubList(temp)
                        }
                    })
                    if (!isRepeat) {
                        new CamerasService()
                            .createCameras({ maker: res.cameraId.maker, model: res.cameraId.model })
                            .then(newCamera => {
                                temp = replaceItemAtIndex(subList, index, {
                                    userId: JSON.parse(localStorage.getItem('account') as any).id,
                                    cameraId: newCamera.data.data.id,
                                    imageUrl: res.imageUrl,
                                    hash: res.hash,
                                    location: res.location,
                                    width: res.width,
                                    height: res.height,
                                    intro: res.intro,
                                    focalLength: 0,
                                    aperture: 0,
                                    iso: 0,
                                    tags: res.tags,
                                    topics: res.topics
                                })
                                setSubList(temp)
                            })
                    }
                })
            }
            new UserService().postPicture(JSON.parse(localStorage.getItem('account') as any).id, {
                userId: JSON.parse(localStorage.getItem('account') as any).id,
                cameraId: res.cameraId,
                imageUrl: res.imageUrl,
                hash: res.hash,
                location: res.location,
                width: res.width,
                height: res.height,
                intro: res.intro,
                focalLength: 0,
                aperture: 0,
                iso: 0,
                tags: res.tags,
                topics: res.topics
            })
        })
    }

    // 图片预览
    const handleFilePreview = async (file: any) => {
        let src = file.url
        if (!src) {
            src = await new Promise(resolve => {
                const reader = new FileReader()
                reader.readAsDataURL(file.originFileObj)
                reader.onload = () => resolve(reader.result)
            })
        }
        const image = new Image()
        image.src = src
        const imgWindow = window.open(src)
        imgWindow!.document.write(image.outerHTML)
    }

    return (
        <ModalView>
            <div
                className={style.container}
                style={{
                    ['--width-' as any]: width,
                    ['--height-' as any]: height,
                    ['--count-' as any]: count
                }}>
                <div className={style.top}>
                    <span>
                        上传至LineView
                        {fileList != '' ? <span style={{ color: '#767676' }}>(按住Shift加滚轮即可滑动)</span> : ''}
                    </span>
                </div>
                <div className={style.center}>
                    <div className={style.content}>
                        <Upload
                            className={style.upload}
                            customRequest={handleUploader}
                            headers={{ 'Content-Type': 'multipart/form-data' }}
                            beforeUpload={beforeUpload}
                            onPreview={handleFilePreview}
                            maxCount={10}
                            showUploadList={false}
                            onChange={({ fileList: newFileList }) => setFileList(fileList)}>
                            <img className={style.sub__icon} src={subPhoto} />
                        </Upload>
                        <span>最多上传{10 - fileList.length}张图片</span>
                    </div>
                    {fileList.map(
                        (item: { hash: string; mime: string; url: string; cameraInfo: any }, index: number) => {
                            return (
                                <div className={style.card} key={index}>
                                    <div
                                        className={style.remove__icon}
                                        onClick={() => {
                                            handleRemoveImg(index)
                                        }}>
                                        <CloseOutlined />
                                    </div>
                                    <SubCard data={item} index={index} />
                                </div>
                            )
                        }
                    )}
                    {fileList == '' ? (
                        <div className={style.bottom__rule}>
                            <div className={style.item}>
                                <ul>
                                    <li>
                                        <b>高质量照片</b>（至少<b>5MP</b>）
                                    </li>
                                    <li>
                                        照片清晰、<b>原汁原味</b>
                                    </li>
                                </ul>
                            </div>
                            <div className={style.item}>
                                <ul>
                                    <li>
                                        只上传<b>你有权上传</b>的照片
                                    </li>
                                    <li>对裸体、暴力或仇恨零容忍</li>
                                </ul>
                            </div>
                            <div className={style.item}>
                                <ul>
                                    <li>尊重他人的知识产权</li>
                                    <li>
                                        阅读<Link to={'/terms'}>LineView条款</Link>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    ) : (
                        ''
                    )}
                </div>
                <div className={style.bottom}>
                    <Link to={'/license'}>阅读LineView许可证</Link>
                    <div className={style.bottom__btn}>
                        <div
                            className={style.cancel__btn}
                            onClick={() => {
                                console.log(subList)
                            }}>
                            取消
                        </div>
                        <div
                            className={`${style.sub__btn} ${fileList != '' ? '' : 'disable'}`}
                            onClick={() => {
                                handleUploadImgData()
                            }}>
                            {fileList != '' ? '上传' + fileList.length + '张图片' : '上传至LineView'}
                        </div>
                    </div>
                </div>
            </div>
        </ModalView>
    )
}
